<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-button type="primary">添加角色</el-button>
      <template>
        <el-table :data="RolesList" border stripe style="width: 100%;">
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row
                class="vcenter"
                v-for="item1 in scope.row.children"
                :key="item1.id"
                :gutter="10"
              >
                <el-col :span="4">
                  <el-tag closable @close="deleteRights(scope.row, item1)">{{
                    item1.authName
                  }}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="20">
                  <el-row
                    v-for="item2 in item1.children"
                    :key="item2.id"
                    class="vcenter"
                  >
                    <el-col :span="8">
                      <el-tag
                        type="success"
                        closable
                        @close="deleteRights(scope.row, item2)"
                        >{{ item2.authName }}</el-tag
                      >
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="16" class="item3">
                      <el-tag
                        closable
                        @close="deleteRights(scope.row, item3)"
                        type="danger"
                        v-for="item3 in item2.children"
                        :key="item3.id"
                        >{{ item3.authName }}</el-tag
                      >
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column prop="roleName" label="角色名称"> </el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>

          <el-table-column>
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="editRole(scope.row)"
              ></el-button>

              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteRole(scope.row.id)"
              ></el-button>

              <el-button
                type="warning"
                icon="el-icon-share"
                size="mini"
                @click="editRights(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>

    <el-dialog title="修改角色信息" :visible.sync="editVisible" width="50%">
      <el-form ref="editRoleForm" :model="editForm" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="ClickEdit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配用户权限" :visible.sync="rightVisible" width="50%" @close="reset">
      <div>用户名称:{{ editForm.roleName }}</div>
      <div>用户描述:{{ editForm.roleDesc }}</div>

      <el-tree :props="props" :data="RightsList" show-checkbox node-key="id" default-expand-all :default-checked-keys	="keys"
      ref="treeRef"> </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="rightVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      RolesList: [],
      editVisible: false,
      rightVisible: false,
      editForm: {
        id: "",
        roleName: "",
        roleDesc: "",
      },
      RightsList: [],
      props: {
        label: "authName",
        children: "children",
      },
      keys:[]
    };
  },
  created() {
    this.getRoles();
  },
  methods: {
    async getRoles() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        this.$message.error("获取角色列表失败");
      } else {
        this.RolesList = res.data;
      }
       console.log(res);
    },

    //修改角色信息
    editRole(data) {
      this.editForm.id = data.id;
      this.editForm.roleName = data.roleName;
      this.editForm.roleDesc = data.roleDesc;
      this.editVisible = true;
      console.log(this.editForm);
    },

    //点击确定发送修改角色信息请求
    async ClickEdit() {
      const { data: res } = await this.$http.put("roles/" + this.editForm.id, {
        roleName: this.editForm.roleName,
        roleDesc: this.editForm.roleDesc,
      });

      if (res.meta.status !== 200) {
        this.$message.error("修改角色失败");
      } else {
        this.getRoles();
        this.$message.success("修改角色成功");
        this.editVisible = false;
      }
      // console.log(res);
    },

    //点击删除角色按钮
    async deleteRole(id) {
      const data = this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "删除角色",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);

      const res = await data;
      // console.log(id)
      if (res !== "confirm") {
        this.$message.info("你取消了删除角色操作");
      } else {
        const { data: res } = await this.$http.delete("roles/" + id);
        if (res.meta.status !== 200) {
          this.$message.error("删除角色失败");
        } else {
          this.getRoles();
          this.$message.success("删除用户成功");
        }
      }
    },

    //点击分配角色权限
    async editRights(data) {
      this.editForm.id = data.id
      this.editForm.roleName = data.roleName;
      this.editForm.roleDesc = data.roleDesc;
      this.rightVisible = true;
      // console.log(data)
      
      // console.log(this.keys)
      const { data: res } = await this.$http.get("rights/tree");

      if (res.meta.status !== 200) {
        this.$message.error("获取权限列表失败");
      } else {
        this.RightsList = res.data;
        this.defaultKeys(data)
      }
    },

    //生成默认权限数组
    defaultKeys(data){
        if(!data.children){
         return this.keys.push(data.id)
        }
        data.children.forEach((item,index)=>{
            this.defaultKeys(item)
            
        })
        
    },

    //点击删除角色的权限
    async deleteRights(role, right) {
      const data = await this.$confirm(
        "此操作将删除该权限, 是否继续?",
        `删除${right.authName}权限`,
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);

      if (data == "confirm") {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${right.id}`
        );

        if (res.meta.status !== 200) {
          this.$message.error("删除" + right.authName + "权限失败");
        } else {
          this.$message.success("删除" + right.authName + "权限成功");
          role.children = res.data;
        }
      } else {
        this.$message.info("你取消了删除权限操作");
      }
    },

    //点击修改角色权限
    async allotRights(){
        // var key = [...this.$refs.treeRef.getHalfCheckedKeys(),...this.$refs.treeRef.getCheckedKeys]

        var key = [...this.$refs.treeRef.getHalfCheckedKeys(),...this.$refs.treeRef.getCheckedKeys()]
        var str = key.join(',')

        const {data:res} = await this.$http.post('roles/'+this.editForm.id+'/rights',{
          rids:str
        })

        if(res.meta.status !== 200){
          return this.$message.error('修改角色权限失败')
        }else{
          this.getRoles()
          this.$message.success('修改角色权限成功')
        }
        console.log(res)

        this.rightVisible = false;
    },
    reset(){
      this.keys = []
    }
  },
};
</script>

<style scoped>
.el-card {
  margin-top: 20px;
  box-shadow: 0 0 1px rgba(0, 0, 0, 0.2);
}

.el-table {
  margin-top: 20px;
}

.el-row {
  margin: 10px;
}

.item3 .el-tag {
  margin: 5px 10px;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
